package sample.crawler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import sample.crawler.base.BaseTask;
import sample.enums.MapType;
import sample.model.Company;
import sample.utils.IndexUtils;
import sample.utils.StringUtils;

public class BaiduTask extends BaseTask {




    public BaiduTask()
    {
        super.mapCode = MapType.baidu.getCode();
    }

    public BaiduTask(String url)
    {
        super.mapCode = MapType.baidu.getCode();
        this.url = url;
    }

    @Override
    public String getUrl(Integer pageNo) {
        //return "http://api.map.baidu.com/place/v2/search?query=" + keywords + "&tag=&region=" + area + "&output=json&ak=RxoisybOPRPMt4vib8q6gmoHrPlptdKZ&page_size="+pageSize+"&page_num=" + pageNo;
        return url.replace("{query}", keywords).replace("{region}", area).replace("{page_size}", pageSize.toString()).replace("{page_num}", pageNo.toString());
    }

    @Override
    public Integer getTotalCount(JSONObject res) {
        return res.getInteger("total");
    }

    @Override
    public void fillTable(JSONObject res) throws Exception {
        if(res.getInteger("status") != 0) {
            throw new Exception(res.getString("message"));
        }
        JSONArray results = res.getJSONArray("results");
        if(results == null)
        {
            throw new Exception("no records");
        }
        for (Object o : results) {
            JSONObject target = (JSONObject) o;

            // 过滤排除关键字
            String name = target.getString("name");
            if(StringUtils.contains(name, exclusiveWords)) {
                continue;
            }

            // 过滤空电话
            String tel = target.getString("telephone");
            if(filterTel && StringUtils.isEmpty(tel)) {
                continue;
            }

            JSONObject location = target.getJSONObject("location");
            StringBuffer locsb = new StringBuffer().append(location.getInteger("lat")).append(",").append(location.getInteger("lng"));

            qrTable.getItems().add(new Company(IndexUtils.getIndex() + "", tel , name, target.getString("province")+ target.getString("city") +target.getString("area"), target.getString("address"), "",
                    keywords, MapType.map.get(mapCode), locsb.toString()));

        }


    }


}
